package com.robotserver.orders.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkAllOrderListIncrementGetRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkOauthOrderDetailGetRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkAllOrderListIncrementGetResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkOauthOrderDetailGetResponse;
import com.robotserver.orders.common.DateFormatUtil;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.entity.PddOrders;
import com.robotserver.orders.enums.BizStatus;
import com.robotserver.orders.mapper.PddOrdersMapper;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.param.PddOrderPullByOrderSnParam;
import com.robotserver.orders.service.PddOrderSyncService;
import com.robotserver.orders.vo.PddConfig;
import com.robotserver.orders.vo.PddOrderTimeVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class PddOrderSyncServiceImpl implements PddOrderSyncService {

    private Logger logger = LoggerFactory.getLogger(PddOrderSyncServiceImpl.class);

    @Autowired
    private PddOrdersMapper pddOrdersMapper;
    @Autowired
    private SysSettingMapper sysSettingMapper;

    @Override
    public void syncUnitOrder(Long begin_time, Long end_time,PddConfig pddConfig) {
        Integer total = getOrders(1,begin_time,end_time,pddConfig);
        if (total != null && total > 0) {
            int pageSize=total / 100 + 1;
            for (int i = pageSize;i >=1; i--) {
                getOrders(i,begin_time,end_time,pddConfig);
            }
        }

        sysSettingMapper.update("pdd_heartbeat",DateUtil.getNowTime()+"");
    }

    private Integer getOrders(int page, Long begin_time, Long end_time,PddConfig pddConfig) {
        Integer total = 0;
        try {
            PopClient client = new PopHttpClient(pddConfig.getPdd_client_id(), pddConfig.getPdd_client_secret());
            PddDdkAllOrderListIncrementGetRequest request = new PddDdkAllOrderListIncrementGetRequest();
            request.setStartUpdateTime(begin_time);
            request.setEndUpdateTime(end_time);
            request.setPageSize(100);
            request.setPage(page);
            PddDdkAllOrderListIncrementGetResponse response = client.syncInvoke(request);
            if (response.getErrorResponse() != null) {
                logger.error("获取订单失败-错误Code:" + response.getErrorResponse().getErrorCode() + ",错误信息:"+response.getErrorResponse().getErrorMsg());
            }
            if (response.getOrderListGetResponse() == null) {
                return 0;
            }
            long ltotal = response.getOrderListGetResponse().getTotalCount();
            total = (int)ltotal;
            logger.info("pdd orders total:{}",total);

            List<PddDdkAllOrderListIncrementGetResponse.OrderListGetResponseOrderListItem> list =  response.getOrderListGetResponse().getOrderList();
            for (int i = 0; i < list.size();i++) {
                PddDdkAllOrderListIncrementGetResponse.OrderListGetResponseOrderListItem item = list.get(i);
                try {
                    orderAdd(item);
                } catch (Exception e) {
                    logger.error("订单入库失败-订单号:" +  item.getCustomParameters()+"::"+item.getOrderSn()+ ",异常信息:", e);
                }
            }
        } catch (Exception e) {
            logger.error("获取订单异常：当前页数:"+page+",异常信息:",e);
        }
        return total;
    }

    @Transactional
    @Override
    public void orderAdd(PddDdkAllOrderListIncrementGetResponse.OrderListGetResponseOrderListItem item) {

        logger.info("----PDD order :ordersn: {},goodsid: {}",new Object[]{item.getOrderSn(),item.getGoodsId()});

        String day = DateFormatUtil.formatDayStr(new Date());
        if ("21".equals(day)){
            if (item.getOrderStatus()!=null &&
                    (item.getOrderStatus().intValue()==3 || item.getOrderStatus().intValue()==5)){
                logger.info("21 order status is :{}",item.getOrderSn());
                // return ;
            }

            if (item.getOrderStatus()!=null && item.getOrderStatus().intValue()==1 && item.getOrderPayTime()!=null){
                if (item.getOrderPayTime().longValue()<DateUtil.getDayBegin()){
                    logger.info("21 order pay time old :{}",item.getOrderSn());
                    // return ;
                }
            }
        }

        //根据订单号判断订单是否已存在。
        int now = DateUtil.getNowTime();
        String ordersn = item.getOrderSn().trim();

        int bizStatus = getStatus(item.getOrderStatus());
        if (bizStatus==-1){
            logger.info("order status is :{}",item.getOrderStatus());
            return ;
        }
        PddOrders pddOrders = pddOrdersMapper.getOrder(ordersn);

        if (pddOrders == null) {
            //没有订单，添加
            pddOrders = new PddOrders();
            pddOrders.setCreateTime(now);
            pddOrders.setUpdateTime(now);
            pddOrders.setId(IdWorker.getId());
            pddOrders.setOrderSn(ordersn);
            pddOrders.setGoodsId(item.getGoodsId());
            pddOrders.setGoodsName(item.getGoodsName());
            pddOrders.setGoodsPrice(item.getGoodsPrice());
            pddOrders.setGoodsThumbnailUrl(item.getGoodsThumbnailUrl());
            pddOrders.setGoodsQuantity(item.getGoodsQuantity().intValue());
            pddOrders.setOrderAmount(item.getOrderAmount());
            pddOrders.setPromotionRate(item.getPromotionRate());
            pddOrders.setPromotionAmount(item.getPromotionAmount());
            pddOrders.setOrderCreateTime(item.getOrderCreateTime());
            pddOrders.setOrderPayTime(item.getOrderPayTime());
            pddOrders.setOrderModifyAt(item.getOrderModifyAt());
            pddOrders.setOrderGroupSuccessTime(item.getOrderGroupSuccessTime());
            pddOrders.setOrderVerifyTime(item.getOrderVerifyTime()==null?0:item.getOrderVerifyTime());
            pddOrders.setOrderStatus(item.getOrderStatus());
            pddOrders.setOrderStatusDesc(item.getOrderStatusDesc());
            pddOrders.setCustomParameters(item.getCustomParameters());
            pddOrders.setIsDirect(item.getIsDirect());
            pddOrders.setpId(item.getPId());
            pddOrders.setBizStatus(bizStatus);
            pddOrders.setSceneAtMarketFee(item.getSceneAtMarketFee());
            pddOrders.setCpaNew(item.getCpaNew());

            if (pddOrders.getBizStatus()== BizStatus.settlement.getValue()){
                pddOrders.setOrderReceiveTime(item.getOrderReceiveTime());
            }

            //modify by liuqi on 20210720
            pddOrders.setPriceCompareStatus(item.getPriceCompareStatus());
            pddOrders.setFailReason(item.getFailReason());
            //modify by liuqi on 20230338
            pddOrders.setSubsidyAmount(item.getSubsidyAmount());
            pddOrders.setSubsidyDuoAmountTenMillion(item.getSubsidyDuoAmountTenMillion());
            pddOrders.setSubsidyDuoAmountLevel(item.getSubsidyDuoAmountLevel());
            pddOrders.setSubsidyType(item.getSubsidyType());
            //modify by liuqi on 20231016
            pddOrders.setZsDuoId(item.getZsDuoId());
            //店铺信息
            pddOrders.setMallId(item.getMallId()==null?null:item.getMallId().toString());
            pddOrders.setMallName(item.getMallName());

            pddOrdersMapper.add(pddOrders);
        } else if (pddOrders.getOrderStatus().intValue()!=item.getOrderStatus().intValue()){        // 订单状态不一致才处理

            pddOrders.setUpdateTime(now);
            pddOrders.setGoodsPrice(item.getGoodsPrice());
            pddOrders.setGoodsThumbnailUrl(item.getGoodsThumbnailUrl());
            pddOrders.setGoodsQuantity(item.getGoodsQuantity().intValue());
            pddOrders.setOrderAmount(item.getOrderAmount());
            pddOrders.setPromotionRate(item.getPromotionRate());
            pddOrders.setPromotionAmount(item.getPromotionAmount());
            pddOrders.setOrderCreateTime(item.getOrderCreateTime());
            pddOrders.setOrderPayTime(item.getOrderPayTime());
            pddOrders.setOrderModifyAt(item.getOrderModifyAt());
            pddOrders.setOrderGroupSuccessTime(item.getOrderGroupSuccessTime());
            pddOrders.setOrderVerifyTime(item.getOrderVerifyTime()==null?0:item.getOrderVerifyTime());
            pddOrders.setOrderStatus(item.getOrderStatus());
            pddOrders.setOrderStatusDesc(item.getOrderStatusDesc());
            pddOrders.setCustomParameters(item.getCustomParameters());
            pddOrders.setpId(item.getPId());
            pddOrders.setBizStatus(bizStatus);
            pddOrders.setSceneAtMarketFee(item.getSceneAtMarketFee());
            pddOrders.setCpaNew(item.getCpaNew());

            if (pddOrders.getBizStatus()== BizStatus.settlement.getValue()){
                pddOrders.setOrderReceiveTime(item.getOrderReceiveTime());
            }

            //modify by liuqi on 20210720
            pddOrders.setPriceCompareStatus(item.getPriceCompareStatus());
            pddOrders.setFailReason(item.getFailReason());

            //modify by liuqi on 20230338
            pddOrders.setSubsidyAmount(item.getSubsidyAmount());
            pddOrders.setSubsidyDuoAmountTenMillion(item.getSubsidyDuoAmountTenMillion());
            pddOrders.setSubsidyDuoAmountLevel(item.getSubsidyDuoAmountLevel());
            pddOrders.setSubsidyType(item.getSubsidyType());

            //modify by liuqi on 20231016
            pddOrders.setZsDuoId(item.getZsDuoId());
            //店铺信息
            pddOrders.setMallId(item.getMallId()==null?null:item.getMallId().toString());
            pddOrders.setMallName(item.getMallName());

            // 更新
            pddOrdersMapper.update(pddOrders);
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder(List<PddOrderTimeVO> pddOrderTimeVOS, PddConfig pddConfig) {
        for (PddOrderTimeVO pddOrderTimeVO:pddOrderTimeVOS){
            syncUnitOrder(pddOrderTimeVO.getBeginTime(),pddOrderTimeVO.getEndTime(),pddConfig);
        }
    }

    private int getStatus(int orderStatus){
        switch (orderStatus){
            case 0:
                return 0;
            case 1:
                return 0;
            case 2:
                return 1;
            case 3:
                return 1;
            case 5:
                return 1;
            case 4:
                return 2;
            case 10:      //违规处罚
                return 8;
        }
        return -1;
    }


    /**
     * 通过订单号下载订单
     * @author liuqi
     * @date 2023/2/1 10:27
     * @param pddOrderPullByOrderSnParam
     * @param pddConfig
     */
    @Override
    public void pullByOrderSn(PddOrderPullByOrderSnParam pddOrderPullByOrderSnParam, PddConfig pddConfig){

        PopClient client = new PopHttpClient(pddConfig.getPdd_client_id(), pddConfig.getPdd_client_secret());

        PddDdkOauthOrderDetailGetRequest request = new PddDdkOauthOrderDetailGetRequest();
        request.setOrderSn(pddOrderPullByOrderSnParam.getOrderSn());
        //request.setQueryOrderType(1); //订单类型：1-推广订单；2-直播间订单
        try {
            PddDdkOauthOrderDetailGetResponse response = client.syncInvoke(request, pddOrderPullByOrderSnParam.getAccessToken());
            PddDdkOauthOrderDetailGetResponse.OrderDetailResponse item = response.getOrderDetailResponse();
            if(item != null){
                //根据订单号判断订单是否已存在。
                int now = DateUtil.getNowTime();
                String ordersn = item.getOrderSn().trim();

                int bizStatus = getStatus(item.getOrderStatus());
                if (bizStatus==-1){
                    logger.info("order status is :{}",item.getOrderStatus());
                    return ;
                }

                PddOrders pddOrders = pddOrdersMapper.getOrder(ordersn);

                if (pddOrders == null) {
                    //没有订单，添加
                    pddOrders = new PddOrders();
                    pddOrders.setCreateTime(now);
                    pddOrders.setUpdateTime(now);
                    pddOrders.setId(IdWorker.getId());
                    pddOrders.setOrderSn(ordersn);
                    pddOrders.setGoodsId(item.getGoodsId());
                    pddOrders.setGoodsName(item.getGoodsName());
                    pddOrders.setGoodsPrice(item.getGoodsPrice());
                    pddOrders.setGoodsThumbnailUrl(item.getGoodsThumbnailUrl());
                    pddOrders.setGoodsQuantity(item.getGoodsQuantity().intValue());
                    pddOrders.setOrderAmount(item.getOrderAmount());
                    pddOrders.setPromotionRate(item.getPromotionRate());
                    pddOrders.setPromotionAmount(item.getPromotionAmount());
                    pddOrders.setOrderCreateTime(item.getOrderCreateTime());
                    pddOrders.setOrderPayTime(item.getOrderPayTime());
                    pddOrders.setOrderModifyAt(item.getOrderModifyAt());
                    pddOrders.setOrderGroupSuccessTime(item.getOrderGroupSuccessTime());
                    pddOrders.setOrderVerifyTime(item.getOrderVerifyTime()==null?0:item.getOrderVerifyTime());
                    pddOrders.setOrderStatus(item.getOrderStatus());
                    pddOrders.setOrderStatusDesc(item.getOrderStatusDesc());
                    pddOrders.setCustomParameters(item.getCustomParameters());
                    pddOrders.setIsDirect(item.getIsDirect());
                    pddOrders.setpId(item.getPid());
                    pddOrders.setBizStatus(bizStatus);
                    pddOrders.setSceneAtMarketFee(item.getSepMarketFee());
                    pddOrders.setCpaNew(item.getCpaNew());

                    if (pddOrders.getBizStatus()== BizStatus.settlement.getValue()){
                        pddOrders.setOrderReceiveTime(item.getOrderReceiveTime());
                    }

                    //modify by liuqi on 20210720
                    pddOrders.setPriceCompareStatus(item.getPriceCompareStatus());
                    pddOrders.setFailReason(item.getFailReason());

                    //modify by liuqi on 20230338
                    pddOrders.setSubsidyAmount(item.getSubsidyAmount());
                    pddOrders.setSubsidyDuoAmountTenMillion(item.getSubsidyDuoAmountTenMillion());
                    pddOrders.setSubsidyDuoAmountLevel(item.getSubsidyDuoAmountLevel());
                    pddOrders.setSubsidyType(item.getSubsidyType());

                    //modify by liuqi on 20231016
                    pddOrders.setZsDuoId(item.getZsDuoId());
                    //店铺信息
                    pddOrders.setMallId(item.getMallId()==null?null:item.getMallId().toString());
                    pddOrders.setMallName(item.getMallName());

                    pddOrdersMapper.add(pddOrders);
                } else if (pddOrders.getOrderStatus().intValue()!=item.getOrderStatus().intValue()){        // 订单状态不一致才处理

                    pddOrders.setUpdateTime(now);
                    pddOrders.setGoodsPrice(item.getGoodsPrice());
                    pddOrders.setGoodsThumbnailUrl(item.getGoodsThumbnailUrl());
                    pddOrders.setGoodsQuantity(item.getGoodsQuantity().intValue());
                    pddOrders.setOrderAmount(item.getOrderAmount());
                    pddOrders.setPromotionRate(item.getPromotionRate());
                    pddOrders.setPromotionAmount(item.getPromotionAmount());
                    pddOrders.setOrderCreateTime(item.getOrderCreateTime());
                    pddOrders.setOrderPayTime(item.getOrderPayTime());
                    pddOrders.setOrderModifyAt(item.getOrderModifyAt());
                    pddOrders.setOrderGroupSuccessTime(item.getOrderGroupSuccessTime());
                    pddOrders.setOrderVerifyTime(item.getOrderVerifyTime()==null?0:item.getOrderVerifyTime());
                    pddOrders.setOrderStatus(item.getOrderStatus());
                    pddOrders.setOrderStatusDesc(item.getOrderStatusDesc());
                    pddOrders.setCustomParameters(item.getCustomParameters());
                    pddOrders.setpId(item.getPid());
                    pddOrders.setBizStatus(bizStatus);
                    pddOrders.setSceneAtMarketFee(item.getSepMarketFee());
                    pddOrders.setCpaNew(item.getCpaNew());

                    if (pddOrders.getBizStatus()== BizStatus.settlement.getValue()){
                        pddOrders.setOrderReceiveTime(item.getOrderReceiveTime());
                    }

                    //modify by liuqi on 20210720
                    pddOrders.setPriceCompareStatus(item.getPriceCompareStatus());
                    pddOrders.setFailReason(item.getFailReason());

                    //modify by liuqi on 20230338
                    pddOrders.setSubsidyAmount(item.getSubsidyAmount());
                    pddOrders.setSubsidyDuoAmountTenMillion(item.getSubsidyDuoAmountTenMillion());
                    pddOrders.setSubsidyDuoAmountLevel(item.getSubsidyDuoAmountLevel());
                    pddOrders.setSubsidyType(item.getSubsidyType());

                    //modify by liuqi on 20231016
                    pddOrders.setZsDuoId(item.getZsDuoId());
                    //店铺信息
                    pddOrders.setMallId(item.getMallId()==null?null:item.getMallId().toString());
                    pddOrders.setMallName(item.getMallName());
                    // 更新
                    pddOrdersMapper.update(pddOrders);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
